import sys
import os
import pexpect

def expectandshow(child, expect):
        index=child.expect(expect)
        print child.before,child.after,
        return index
order=[]

password="passw0rd"

fp_intr = open('/root/vmimage/mpi_paas/code/ip','r')
#while True:
#    	line = fp_intr.readline()
#    	length = len(line)
#
#	if length == 0: # Zero length indicates EOF
#        	break
#    	
#	line=line[0:length-1] 
#	print line
#	order.append(line)
master_ip=fp_intr.readline()
length=len(master_ip)
master_ip=master_ip[0:length-1]
fp_intr.close();



cmd = "ssh root@" + master_ip + " " + \
	"mpdboot; mpdtrace -l;"

	
print cmd

scp_child=pexpect.spawn(cmd)

fout = file('mylog','w')
scp_child.logfile = fout

index=expectandshow(scp_child, \
                    ['Are you sure you want to continue connecting', \
                   "root@"+master_ip+"'s password:", \
                   pexpect.TIMEOUT, \
                   pexpect.EOF])
if index == 0:
     	scp_child.sendline('yes')
        ret = expectandshow(scp_child, ["root@"+master_ip+"'s password:", pexpect.EOF])
        if ret == 0:
                scp_child.sendline(password)
                expectandshow(scp_child, [pexpect.EOF])
        elif ret == 1:
                pass
elif index == 1:
        scp_child.sendline(password)
        expectandshow(scp_child, [pexpect.EOF])
elif index == 2:
        print "timeout, ignore and continue."
elif index == 3:
        pass

fp_intr=open('/root/vmimage/mpi_paas/code/mylog','r')
fp_intr.readline()
line1=""
while True:
	line=fp_intr.readline()
	length=len(line)
	if length==0:
		break
	if length > 1:
		line1=line[0:length-1]
		print line1
		
fp_intr.close()


print line1
master=""
port=""
l = len(line1)
flag1 = 0;
for i in range(0,l):
	if line1[i] == '_':
		master=line1[0:i]
		flag1 = i+1;
	elif line1[i] == ' ':
		port = line1[flag1:i];
		break

print master
print port


fp_intr=open('/root/vmimage/mpi_paas/code/ip','r')
fp_intr.readline()
while True:
	ip=fp_intr.readline()
	length=len(ip)
	if length == 0:
		break
	ip=ip[0:length-1]
	
	cmd = "ssh root@" + ip + " nohup " + \
        "mpd -h "+master+" -p "+port+ " &"
	print cmd

	scp_child=pexpect.spawn(cmd)
	index=expectandshow(scp_child, \
                    ['Are you sure you want to continue connecting', \
                   "root@"+ip+"'s password:", \
                   pexpect.TIMEOUT, \
                   pexpect.EOF])
	if index == 0:
        	scp_child.sendline('yes')
        	ret = expectandshow(scp_child, ["root@"+ip+"'s password:", pexpect.EOF])
        	if ret == 0:
                	scp_child.sendline(password)
                	#expectandshow(scp_child, [pexpect.EOF])
        	elif ret == 1:
                	pass
	elif index == 1:
        	scp_child.sendline(password)
       	 	#expectandshow(scp_child, [pexpect.EOF])
	elif index == 2:
        	print "timeout, ignore and continue."
	elif index == 3:
        	pass








